# coding: utf-8
import json

import requests
from flask import request, Blueprint, current_app

from bluesky.model.User import User
from bluesky.util import dto, biz
from extentions import db

user_blue = Blueprint('user', __name__, url_prefix='/')


@user_blue.route("/code_login", methods=['POST'])
def login():
    """
    qq 登录，没有账号注册
    :param
        code
        avatar
        nickname
    """
    data = request.get_json()
    code = data.get('code')
    if not code:
        return {'code': 1, 'msg': 'code is null'}
    openid = get_open_id(code)
    if not openid:
        return {'code': 1, 'msg': 'openid is null'}

    with db.with_session() as session:
        u = session.query(User).filter(User.openid == openid).first()
        if not u:
            # 注册
            u = User(
                nickname=data.get('nickname') or '',
                avatar=data.get('avatar') or '',
                openid=openid
            )
            session.add(u)
        result = dto.user_dto(u)
        result['token'] = biz.generate_token(u)
    return {'code': 0, 'data': result}


@user_blue.route("/user/current", methods=['GET'])
def current_user():
    token = request.headers.get('Authorization')
    if not token:
        return {'code': 3, 'msg': 'token not found'}
    token_data = biz.decode_token(token)
    user_id = token_data.get('id')

    with db.with_session() as session:
        u = session.query(User).filter(User.id == user_id).first()
        if not u:
            return {'code': 2, 'msg': 'user not found'}
        result = dto.user_dto(u)

    return {'code': 0, 'data': result}


@user_blue.route("/user", methods=['POST'])
def create_user():
    data = request.get_json()

    u = User(username=data.get('name'), nickname=data.get('nickname'))
    with db.with_session() as session:
        session.add(u)

    return {'code': 0, 'data': dto.user_dto(u)}


@user_blue.route("/user", methods=['GET'])
def get_users():
    id = request.args.get('id')
    name = request.args.get('name')

    with db.with_session() as session:
        query = session.query(User)
        query = query if biz.empty(id) else query.filter(User.id == id)
        query = query if biz.empty(name) else query.filter(User.nickname == name)
        users = query.all()

    return {'code': 0, 'data': dto.user_dtos(users)}


def get_open_id(code):
    app = current_app
    app_id = app.config["QQ_APP_ID"]
    app_secret = app.config["QQ_APP_SECRET"]
    url = f'https://api.q.qq.com/sns/jscode2session?appid={app_id}&secret={app_secret}&js_code={code}&grant_type=authorization_code'
    res = requests.get(url)
    print(f'get_open_id result {res.status_code}   {res.text}')
    if res.status_code != 200:
        return
    data_json = json.loads(res.text)
    openid = data_json['openid']
    return openid
